package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.attr;

import com.iwhalecloud.bss.kite.client.api.scene.operate.IOperateSceneCommonService;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.client.vo.scene.CommonAttrVO;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.constant.ServiceOfferConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.CuccPosServiceUtils;
import com.iwhalecloud.bss.kite.dataservice.cache.AttrValueCache;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.dataservice.entity.AttrValue;
import com.iwhalecloud.bss.kite.dataservice.entity.DcPublic;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.Offer;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.iwhalecloud.bss.kite.web.service.accept.attr.handler.AbstractAttrHandler;
import com.ztesoft.bss.common.util.SpringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Service
public class StartRentWayAttrHandler extends AbstractAttrHandler {

    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Autowired
    private IOperateSceneInstService operateSceneInstService;

    private static final String RATESCHANGE_SERVICCEOFFER = "1009"; //资费变更业务

    private static final String DATA_CORRECTION = "1080";//资料修正

    @Override
    public void init(CommonAttrVO commonAttr) {
        String sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
        KiteSceneInst kiteSceneInst = querySceneInstService.getSceneInst(sceneInstId);
        String serviceOfferId = Optional.ofNullable(kiteSceneInst).map(KiteSceneInst::getServiceOfferId).orElse("");

        boolean flag = false;
        if(KiteStringUtils.isEqual(serviceOfferId, ServiceOfferConsts.SERVICE_OFFER_ORDER)) {
            flag = true;
        } else if(KiteStringUtils.isEqual(serviceOfferId, ServiceOfferConsts.SERVICE_OFFER_MODIFY)) {
            // 获取页面勾选的操作类型
            List<String> serviceOfferIdList = querySceneInstService.getExtParameterValue(sceneInstId, "BUSI_CHANGE_SERVICEOFFERID");
            if (KiteListUtils.isNotEmpty(serviceOfferIdList) && serviceOfferIdList.size() == 1 && serviceOfferIdList.contains(RATESCHANGE_SERVICCEOFFER)) {
                flag = true;
            }
        }

        // 五大双线落地方产品 订购、变更仅选资费变更操作类型，起租方式只能为自动起租
        if(flag) {
            String custId = KiteWebContext.getContext().getCust().getCustId();
            KiteInst kiteInst = querySceneInstService.getKiteInst(custId, kiteSceneInst.getRootInstType(), kiteSceneInst.getRootInstId());

            List<DcPublic> list = DcPublicCache.get("20210719001");
            // 是否五大双线落地方产品
            flag = (list != null) && list.stream().anyMatch(dcPublic -> KiteStringUtils.isEqual(kiteInst.getSpecId(), dcPublic.getCodeb()));
            if (flag) {
                operateSceneInstService.putExtParameter(sceneInstId, "fallPlaceStartRentWay", KeyConsts.IFTRUE_F);

                String valueDesc = Optional.ofNullable(AttrValueCache.getAttrValue(commonAttr.getAttrId(), "1")).map(AttrValue::getAttrValueName).orElse("自动起租");
                commonAttr.setValue("1");
                commonAttr.setValueDesc(valueDesc);
                commonAttr.setIsEdit(KeyConsts.IFTRUE_F);

                KiteAttr startRentWayAttr = querySceneInstService.getCommonAttr(sceneInstId, LocalKeyConsts.START_RENT_WAY);
                startRentWayAttr.setValue("1");
                startRentWayAttr.setValueDesc(valueDesc);
                startRentWayAttr.setIsEdit(KeyConsts.IFTRUE_F);
                operateSceneInstService.setCommonAttr(sceneInstId, startRentWayAttr);
                setCommonAttr(commonAttr);
                return;
            }
        }
        operateSceneInstService.removeExtParameter(sceneInstId, "fallPlaceStartRentWay");

        initAttrValue(commonAttr, sceneInstId);
        initAttrStyle(commonAttr, sceneInstId);
    }

    @Override
    public DataResult<Boolean> apply(String sceneInstId, String fieldName, String value, String valueDesc) {
        List<String> serviceOfferIdList = querySceneInstService.getExtParameterValue(sceneInstId, "BUSI_CHANGE_SERVICEOFFERID");//获取页面勾选的操作类型
        KiteSceneInst sceneInst = querySceneInstService.getSceneInst(sceneInstId);
        String serviceOfferId = sceneInst.getServiceOfferId();
        KiteAttr rentWayAttr = querySceneInstService.getCommonAttr(sceneInstId, LocalKeyConsts.START_RENT_WAY);
        if (Objects.nonNull(rentWayAttr)) {
            if (ServiceOfferConsts.SERVICE_OFFER_MODIFY.equals(serviceOfferId)) {
                if (KiteListUtils.isNotEmpty(serviceOfferIdList) && serviceOfferIdList.contains(DATA_CORRECTION) && serviceOfferIdList.size() == 1) {
                    rentWayAttr.setIsEdit(KeyConsts.IFTRUE_F);
                    rentWayAttr.setValue("0");
                } else if (KiteListUtils.isNotEmpty(serviceOfferIdList) && serviceOfferIdList.contains(RATESCHANGE_SERVICCEOFFER) && serviceOfferIdList.size() == 1) {
                    rentWayAttr.setIsEdit(KeyConsts.IFTRUE_F);
                } else {
                    String fallPlaceStartRentWay = querySceneInstService.getExtParameterValue(sceneInstId, "fallPlaceStartRentWay");
                    if(!KiteStringUtils.isEqual(fallPlaceStartRentWay, KeyConsts.IFTRUE_F)) {
                        rentWayAttr.setIsEdit("T");
                    }
                    // 变更操作类型传进来的value为空，重新选择属性时，value值不为空
                    rentWayAttr.setValue(KiteStringUtils.isNotEmpty(value) ? value : "1");
                }
                valueDesc = Optional.ofNullable(AttrValueCache.getAttrValue(rentWayAttr.getAttrId(), rentWayAttr.getValue()))
                    .map(AttrValue::getAttrValueDesc).orElse(valueDesc);
                rentWayAttr.setValueDesc(valueDesc);
                return SpringUtil.getBean(IOperateSceneCommonService.class).setCommonAttr(sceneInstId, rentWayAttr);
            }
            return super.apply(sceneInstId, fieldName, value, valueDesc);
        }
        return super.apply(sceneInstId, fieldName, value, valueDesc);
    }

    private void initAttrValue(CommonAttrVO commonAttr, String sceneInstId) {
        //非录入环节界面不再设置默认值
        String nodeCode = querySceneInstService.getExtParameterValue(sceneInstId, "nodeCode");
        if (KiteStringUtils.isNotEmpty(nodeCode)) {
            // 处理非录入环节值会被DefaultValue覆盖问题
            if (KiteStringUtils.isNotEmpty(commonAttr.getOriginValue())) {
                setAttrValue(commonAttr, commonAttr.getOriginValue());
                commonAttr.setDefaultValue(commonAttr.getOriginValue());
                setCommonAttr(commonAttr);
            }
            return;
        }
        KiteSceneInst sceneInst = querySceneInstService.getSceneInst(sceneInstId);
        String serviceOfferId = sceneInst.getServiceOfferId();
        String postProvinceNbr = sceneInst.getProvinceNbr();
        if (KiteStringUtils.equalsAny(serviceOfferId, "1004", "1048", "2829")) {
            if (KiteStringUtils.equalsAny(postProvinceNbr,LocalKeyConsts.PROVINCE_SHANGHAI,LocalKeyConsts.PROVINCE_SHANDONG)) {
                // 上海五大双线 复机时的起租：默认“自动起租”
                setAttrValue(commonAttr, "1");
                commonAttr.setDefaultValue("1");
            } else {
                setAttrValue(commonAttr, "0");
                commonAttr.setDefaultValue("0");
            }
        } else if (KiteStringUtils.isEqual(serviceOfferId, "1024")) {
            if (KiteStringUtils.isEqual(postProvinceNbr, LocalKeyConsts.PROVINCE_LIAONING)) {
                // 辽宁 附加商品变更 起租方式=自动起租，不可修改
                setAttrValue(commonAttr, "1");
            }
        } else if (!KiteStringUtils.equalsAny(serviceOfferId, "1004", "1048", "1003", "1047", "1005", "2829", "2830", "1080")) {

            if (KiteStringUtils.equals(LocalKeyConsts.PROVINCE_SHANGHAI, postProvinceNbr)) {
                // 上海 订购、变更时的起租：默认“手动起租”；“手动起租”，“自动起租”两个取值都有
                setAttrValue(commonAttr, "0");
                commonAttr.setDefaultValue("0");
            } else {
                List<String> serviceOfferIdList = querySceneInstService.getExtParameterValue(sceneInstId, "BUSI_CHANGE_SERVICEOFFERID");//获取页面勾选的操作类型
                if (KiteListUtils.isNotEmpty(serviceOfferIdList) && serviceOfferIdList.contains(RATESCHANGE_SERVICCEOFFER) && serviceOfferIdList.size() == 1) {
                    commonAttr.setDefaultValue("1");
                    setAttrValue(commonAttr, "1");
                }
            }
            // 订购 起租方式默认为“手动起租”，自动起租，手动起租都有
            if (KiteStringUtils.equals(LocalKeyConsts.PROVINCE_HUNAN, postProvinceNbr) && KiteStringUtils.equalsAny(serviceOfferId, "1")) {
                setAttrValue(commonAttr, "0");
                commonAttr.setDefaultValue("0");
            }
        }
        if (KiteStringUtils.equals(LocalKeyConsts.PROVINCE_SHANDONG,postProvinceNbr) && KiteStringUtils.equalsAny(serviceOfferId,"1","2826")){
            //山东 订购、变更、复机 起租方式默认为“自动起租”,
            setAttrValue(commonAttr, "1");
            commonAttr.setDefaultValue("1");
        }
        //提交到缓存
        setCommonAttr(commonAttr);
    }

    private void initAttrStyle(CommonAttrVO commonAttr, String sceneInstId) {
        KiteSceneInst sceneInst = querySceneInstService.getSceneInst(sceneInstId);
        String serviceOfferId = sceneInst.getServiceOfferId();
        String postProvinceNbr = sceneInst.getProvinceNbr();
        if (KiteStringUtils.equalsAny(serviceOfferId, "1004", "1048", "2829")) {
            if (KiteStringUtils.equals(LocalKeyConsts.PROVINCE_HUNAN, postProvinceNbr)) {
                commonAttr.setIsEdit(KeyConsts.IFTRUE_T);
            }
        } else if (KiteStringUtils.isEqual(serviceOfferId, "1024")) {
            if (KiteStringUtils.isEqual(postProvinceNbr, LocalKeyConsts.PROVINCE_LIAONING)) {
                // 辽宁 附加商品变更 起租方式=自动起租，不可修改
                commonAttr.setIsEdit(KeyConsts.IFTRUE_F);
            }
        } else if (!KiteStringUtils.equalsAny(serviceOfferId, "1004", "1048", "1003", "1047", "1005", "2829", "2830")) {
            // 订单性质（5：绿色工单；2：补录单；8：资料修正单），不可修改起租方式
            String orderNature = querySceneInstService.getCommonAttrValue(sceneInstId, LocalKeyConsts.ORDER_NATURE);
            if (KiteStringUtils.equalsAny(orderNature, "2", "5", "8")) {
                commonAttr.setIsEdit(KeyConsts.IFTRUE_F);
            } else {

                if (KiteStringUtils.equals(LocalKeyConsts.PROVINCE_SHANGHAI, postProvinceNbr)) {
                    commonAttr.setIsEdit(KeyConsts.IFTRUE_T);
                } else {
                    List<String> serviceOfferIdList = querySceneInstService.getExtParameterValue(sceneInstId, "BUSI_CHANGE_SERVICEOFFERID");//获取页面勾选的操作类型
                    if (KiteListUtils.isNotEmpty(serviceOfferIdList) && serviceOfferIdList.contains(RATESCHANGE_SERVICCEOFFER) && serviceOfferIdList.size() == 1) {
                        commonAttr.setIsEdit(KeyConsts.IFTRUE_F);
                    } else {
                        commonAttr.setIsEdit(KeyConsts.IFTRUE_T);
                    }
                }

            }
        }
        //山东 订购、变更、复机 可编辑
        if (KiteStringUtils.equals(LocalKeyConsts.PROVINCE_SHANDONG,postProvinceNbr) && KiteStringUtils.equalsAny(serviceOfferId,"1","2826","2829","1004","1048")){
            commonAttr.setIsEdit(KeyConsts.IFTRUE_T);
        }

        // 国际以太网、国际互联网，订购/变更签订环节（不包括核查转定），不能修改起租方式
        if(KiteStringUtils.equalsAny(serviceOfferId,"1","2826")) {
            String offerId = querySceneInstService.getOfferInst(sceneInst.getCustId(), sceneInst.getRootInstId()).getOfferId();
            String nodeCode = querySceneInstService.getExtParameterValue(sceneInstId, "nodeCode");
            // 是否核查转定
            String isTransferOrderScene = querySceneInstService.getExtParameterValue(sceneInstId, "isTransferOrderScene");
            if((KiteStringUtils.isEqual(nodeCode, "OrderSigned") && !KiteStringUtils.isEqual(isTransferOrderScene, "T") || KiteStringUtils.isEqual(nodeCode, "OrderResubmit"))
                && KiteStringUtils.equalsAny(offerId, "50040654","50040655","50040657","50040853")) {
                commonAttr.setIsEdit(KeyConsts.IFTRUE_F);
            }
        }

        //提交到缓存
        setCommonAttr(commonAttr);

        // 修改实例中的值
        KiteAttr startRentAttr = querySceneInstService.getCommonAttr(sceneInstId, LocalKeyConsts.START_RENT_WAY);
        if (Objects.nonNull(startRentAttr)) {
            startRentAttr.setIsEdit(commonAttr.getIsEdit());
            operateSceneInstService.setCommonAttr(sceneInstId, startRentAttr);
        }
    }

    private void setAttrValue(CommonAttrVO commonAttr, String value) {
        commonAttr.setValue(value);
        String commonDesc = Optional.ofNullable(AttrValueCache.getAttrValue(commonAttr.getAttrId(), commonAttr.getValue()))
            .map(AttrValue::getAttrValueName).orElse(commonAttr.getValue());
        commonAttr.setValueDesc(commonDesc);
    }
}
